<template>
  <el-card class="login-card__body"
           shadow="never">
    <div slot="header">
      <h3 class="login-title">欢迎登录</h3>
    </div>
    <el-form ref="loginForm"
             label-position="top"
             :model="form"
             :rules="rules"
             label-width="80px"
             class="login-box">
      <el-form-item label="账号"
                    prop="account">
        <el-input type="text"
                  placeholder="请输入账号"
                  v-model="form.account" />
      </el-form-item>
      <el-form-item label="密码"
                    prop="password">
        <el-input type="password"
                  placeholder="请输入密码"
                  v-model="form.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :loading="loading"
                   @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  title: '登录页 | 快来加入我们吧~',
  data () {
    return {
      form: {
        account: '',
        password: ''
      },
      loading: false,
      rules: {
        account: [
          { required: true, message: '账号不可为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('login', ['logined'])
  },
  created () {
    if (this.logined === true) {
      this.redirectHome()
    }
  },
  methods: {
    ...mapActions('login', ['token']),
    async login () {
      await this.$refs.loginForm.validate()
      this.loading = true
      this.token(this.form).then((r)=>{}).catch((e)=>{}).finally(()=> {
          this.loading = false
      })
    },
    redirectHome () {
      this.$router.push({ path: '/' })
    }
  },
  watch: {
    logined (newVal, oldVal) {
      if (newVal === true) {
        this.redirectHome()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.login-card__body {
  height: 400px;
  min-width: 600px;
  text-align: left;
  margin-top: 120px;
}
.login-title {
  text-align: center;
  margin: 0;
}
</style>
